//
//  HomeViewController.swift
//  Stauts
//
//  Created by Kylin on 16/3/12.
//  Copyright © 2016年 Kylin. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class HomeViewController: BaseViewContoller {

    // MARK:- 懒加载属性
    private lazy var titleBtn : titleButton = titleButton(type: .Custom)
    private lazy var popoverAnimtor : PopoverAnimator = PopoverAnimator() // 动画管理对象
    private lazy var statusItemViewModel : [HomeStatusItemViewModel] = [HomeStatusItemViewModel]()
    private lazy var cellHeightCache : [String : CGFloat] = [String : CGFloat]()
    private lazy var tipLabel : UILabel = UILabel()
    private lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator()
    
    // MARK:- 系统加调方法
    override func viewDidLoad() {
        super.viewDidLoad()

          // 1.判断用户是否登录
        if !isLogin {
            visitorView.addRotationAnimate()
          return
        }
       
        // 2:初始化导航栏
        setupNavgationBar()
        
        // 3:添加用于提示微博个数的Label
        setupTipLabel()
        
        // 4:下拉刷新
        setupHeaderView()
        
        // 5.监听图片发生点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.showPhotoBrowser(_:)), name: showPhotoBrowserVcNote, object: nil)
    
    }

}

// MARK:- 设置UI
extension HomeViewController {
    private func setupNavgationBar () {
        
        //1 设置左侧的Item
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", taget: self, action: #selector(HomeViewController.leftBtnClick))
        // 2.设置右侧的Item
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", taget: self, action: #selector(HomeViewController.rightBtnClick))
        
        
        // 3:设置标题按钮
        titleBtn.setTitle("kylinSpace", forState: .Normal)
        titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick(_:)), forControlEvents: .TouchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    private func setupHeaderView () {
        
        // 1:添加HeaderView
        let headerView = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewData))
        
        headerView.setTitle("下拉可以刷新", forState: .Idle)
        headerView.setTitle("松开立即刷新", forState: .Pulling)
        headerView.setTitle("加载刷新中...", forState: .Refreshing)
        tableView.mj_header = headerView
        
        //2:进入刷新状态
        headerView.beginRefreshing()
        //1:将Label添加到父控件
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        //2:设置Frame
        tipLabel.frame = CGRect(x: 0, y: 12, width: UIScreen.mainScreen().bounds.width, height: 32)
        // 3.设置tipLabel的属性
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.font = UIFont.systemFontOfSize(14)
        tipLabel.textAlignment = .Center
        tipLabel.hidden = true
    }
    
    // 添加用于提示微博的个数的Label
    private func setupTipLabel () {
        
    }
}

// MARK:- POPover动画设置
extension HomeViewController {
    @objc private func leftBtnClick () {
        print("leftBtnClick")
    }
    
    @objc private func rightBtnClick () {
        print("rightBtnClick")
    }
    
    @objc private func titleBtnClick (titleBtn : titleButton) {
        
        // 创建PopoverVc
        let popoverVc = PopoverViewController()
        // 2.设置PopoverVc的modal样式为自定义(弹出控制器后,后面的View不会被系统隐藏)
        popoverVc.modalPresentationStyle = .Custom
        
        // 设置转场的代理
     
        popoverAnimtor.presentedFrame =  CGRect(x: 90, y: 55, width: 200, height: 280)
        popoverAnimtor.animateCallBack = { [weak self] (isPresented : Bool) -> () in
            
         self?.titleBtn.selected = isPresented
        }
        
        popoverVc.transitioningDelegate = popoverAnimtor
        
        // 弹出控制器
     presentViewController(popoverVc, animated: true, completion: nil)
        
    }
    
    // MARK:- 接收通知执行的方法
    @objc private func showPhotoBrowser(note : NSNotification) {
         // 1.取出indexPath,picURLs
        guard let indexPath = note.userInfo![showPhotoBrowserVcNoteIndex] as? NSIndexPath,picURLs = note.userInfo![showPhotoBrowserVcNotePicURLs] as? [NSURL],objct = note.object as? PicCollectionView else {
            return
        }
        // 2.创建图片浏览器的控制器
        let photoBrowserVc = PhotoBrowserController(indexPath: indexPath, picURLs: picURLs)
        // 3.设置modal样式是.custom
        photoBrowserVc.modalPresentationStyle = .Custom
        // 4:设置转场动画代理
        photoBrowserVc.transitioningDelegate = photoBrowserAnimator
        // 5.设置photoBrowserAnimator的属性
        photoBrowserAnimator.presentedDelegate = objct
        photoBrowserAnimator.dismissDelegate = photoBrowserVc
        photoBrowserAnimator.indexPath = indexPath
        
        
        // 弹出图片浏览器的控制器
        presentViewController(photoBrowserVc, animated: true, completion: nil)
    }
}

// MARK:- tableView的数据源方法
extension HomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        return statusItemViewModel.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 1:创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier("homeCell")as! HomeCell
        
        //2:给Cell设置数据
        cell.statusItemViewModel = statusItemViewModel[indexPath.row]
        
        // 3.判断释放最后一个cell
        if indexPath.row == statusItemViewModel.count - 1 {
            loadMoreData()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 0.取出模型对象
        let statusViewModel = statusItemViewModel[indexPath.row]
        
        // 1.先从缓存池中取出高度
        var cellHeight : CGFloat? = cellHeightCache["\(statusViewModel.statusItem!.id)"]
        if cellHeight != nil {
            return cellHeight!
        }
        
        // 2.取出indexPath对应的cell
        let cell = tableView.dequeueReusableCellWithIdentifier("homeCell") as! HomeCell
        
         // 3.获取cell的高度
        cellHeight = cell.cellHeight(statusViewModel)
        
        // 4.缓存高度
        cellHeightCache["\(statusViewModel.statusItem?.id)"] = cellHeight!
        
        return cellHeight!
    }
}

// MARK:- 网络请求
extension HomeViewController {
    // 请求最新的数据
    @objc private func loadNewData () {
        loadHomeStatuses(true)
    }
    
    // 请求更多数据
    @objc private func loadMoreData () {
        loadHomeStatuses(false)
    }
    /// 请求首面数据
    
    private func loadHomeStatuses (isNewData : Bool) {
        
        // 1:获取请求参数
        var since_id : Int = 0
        var max_id : Int = 0
        
        if isNewData {
            since_id = statusItemViewModel.first?.statusItem?.id ?? 0
        }else {
            max_id = statusItemViewModel.last?.statusItem?.id ?? 0
            max_id = max_id == 0 ? 0 : max_id - 1
        }
        NetworTools.shareManager.loadStatuses(since_id,max_id: max_id) {(result, error) -> () in
            
            // 1.错误检验
            if error != nil {
                print(error)
                self.tableView.mj_header.endRefreshing()
                return
            }
            
            // 2:判断数组是否有值
            guard let resultArray = result else {
                self.tableView.mj_header.endRefreshing()
                return
            }
            
            // 3.遍历数组,将数组中的字典转成模型对象
            var models = [HomeStatusItemViewModel]()
            for resultDict in resultArray {
                // 调用模型的构造方法,遍历字典key为模型的属性赋值
                let statusItem = HomeStatusItem(dict: resultDict)
                let statusItemViewModel = HomeStatusItemViewModel(statusItem: statusItem)
                models.append(statusItemViewModel)
            }
            
            if isNewData {
                self.statusItemViewModel = models + self.statusItemViewModel
            }else {
                self.statusItemViewModel += models
            }
            //4: 缓存图片
            self.cacheImage(models)
           
        }
    }
    
    // 异步请求的组的使用,将所有异步请求放入一个组中,等到完成所有下载后,再更新表表格
    // 缓存图片
    private func cacheImage (models : [HomeStatusItemViewModel]) {
        //0.创建group
        let group = dispatch_group_create()
        // 1.缓存图片
        // 1.1.遍历所有的微博
        for statusItem in models {
            // 1.2.遍历所有的微博中url
            for url in statusItem.picURLs {
                // 1.3.将异步请求加载group中
                dispatch_group_enter(group)
                // 1.4.缓存图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _ , _, _) -> Void in
                    // 1.5.将异步处理从group中移除掉
                    dispatch_group_leave(group)
                })
            }
        }
        
         // 刷新表格
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            // 1:刷新表格
            self.tableView.reloadData()
        
            // 2:停止刷新
            self.tableView.mj_header.endRefreshing()
            
            // 3.显示Label并执行动画
           self.showTipLabelAnim(models.count)
    
        }
    }
    
    /// 显示提示Label
    private func showTipLabelAnim (count : Int) {
        // 1.设置tipLabel的属性
        tipLabel.hidden = false
        tipLabel.text = count == 0 ? "没有新微博" :"\(count) 条新微博"
        // 2.执行动画
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateWithDuration(1.0, delay: 1.0, options: [], animations: { () -> Void in
                    self.tipLabel.frame.origin.y = 12
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        }
        
    }
}








